package com.fjwt.gz.province.changchun;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.aliyun.oss.common.utils.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.core.interfaces.UserAssetService;
import com.fjwt.gz.province.changchun.encrypt.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 资产等级、绑卡消费  资产等级接口：长春返回的是0~5
 */
@Slf4j
@Service
public class JilinUserAssetService implements UserAssetService {
    private JSONObject getAssetConsumption(List custNolist, String url, int year, int lastMonth) throws Exception {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, lastMonth - 1, 1); // 设置年份和月份，注意月份是从0开始的
        Date currentDate = calendar.getTime();
        log.debug("需要查询的实名id：custNolist ：{}", custNolist);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
        String dateStr = dateFormat.format(currentDate);
        log.debug("需要查询的时间：dateStr ：{}", dateStr);
        HttpResponse response = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
        List list = new ArrayList();
        Map params = new HashMap();
        for (int i = 0; i < custNolist.size(); i++) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("custNo", String.valueOf(custNolist.get(i)));
            jsonObject.put("startDate", dateStr);
            String encryption = AesUtil.encrypt(String.valueOf(jsonObject));
            list.add(encryption);
            params.put("param" + (i + 1), encryption);
        }
        String json = objectMapper.writeValueAsString(list);
        log.debug("JSON RequestBody: {}", json);

        String sign = SignatureUtil.generateSignature(params, SignVerifyFilter.SECRET_KEY);
        Boolean a = SignatureUtil.verifySignature(params, SignVerifyFilter.SECRET_KEY, sign);
        log.debug("验签结果：{}",a);
        log.debug("接口地址：{}", url);
        HttpRequest body = HttpRequest.post(url)
                .header("Content-Type", "application/json;charset=utf-8")
                .header(SignVerifyFilter.SIGNATURE_HEADER, sign)
                .timeout(10000)
                .body(json);
        response = body.execute();
        }catch (Exception e){
            e.printStackTrace();
            throw new BizException("网络连接异常,请稍后重试");
        }
        if(response==null){
            throw new BizException("网络连接异常,请稍后重试");
        }
        RsaFgmUtils rsaFgmUtils = new RsaFgmUtils();
        JSONObject respData = JSONObject.parseObject(response.body());
        log.debug("响应结果：{}", response);
        String code = respData.getString("code");
        if ("200".equals(code)){
            String decrypt = null;
            try {
                decrypt = rsaFgmUtils.decryptByPublicKey(RsaFgmUtils.publicKey, respData.getString("data"));
            } catch (Exception e) {
                e.printStackTrace();
                throw new BizException("数据解密失败");
            }
            if(StringUtils.isNullOrEmpty(decrypt)){
                throw new BizException("数据解密失败");
            }
            JSONArray decryptlist = objectMapper.readValue(decrypt, JSONArray.class);
            log.debug("解密后,用户情况：decryptlist：{}", decryptlist);
            return decryptlist.getObject(0, JSONObject.class);
        }else {
            throw new BizException(String.valueOf(response));
        }

    }

    /**
     * 资产等级
     */
    @Override
    public Integer userAssetLevel(@NonNull String cstmNo, int year, int lastMonth) {
        log.debug("需要查询的用户实名cstmNo：{}", cstmNo);
        List<String> cstmNoList=new ArrayList<>();
        cstmNoList.add(cstmNo);
        try {
            JSONObject jsonObject = this.getAssetConsumption(cstmNoList, ChangchunKit.USER_ASSET_SITUATION_URL,year,lastMonth);
            log.debug("用户资产等级：{}", jsonObject);
            if(jsonObject!=null&& !StringUtils.isNullOrEmpty(jsonObject.getString("assetClass"))){
                return jsonObject.getInteger("assetClass");
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("用户资产等级数据查询失败：{}", e);
        }
        return null;
    }

    @Override
    public JSONObject userAssetLevelList(List cstmNolist) {
        return null;
    }

    /**
     * 绑卡消费
     */
    @Override
    public Integer userConsumption(@NonNull String cstmNo, int year, int lastMonth) {
        log.debug("需要查询的用户实名cstmNo：{}", cstmNo);
        List<String> cstmNoList=new ArrayList<>();
        cstmNoList.add(cstmNo);
        try {
            JSONObject jsonObject = this.getAssetConsumption(cstmNoList, ChangchunKit.CONSUMPTION_STATISTICS_URL,year,lastMonth);
            log.debug("用户绑卡消费：{}", jsonObject);
            if(jsonObject!=null&& !StringUtils.isNullOrEmpty(jsonObject.getString("countNum"))){
                return jsonObject.getInteger("countNum");
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("用户绑卡消费数据查询失败：{}", e);
        }
        return null;
    }

    @Override
    public JSONObject userConsumptionList(List cstmNolist) {
        return null;
    }

    /**
     * 季度资产等级
     */
    @Override
    public Integer quarterUserAssetLevel(@NonNull String custNum, int year, int quarter) {
        log.debug("需要查询的用户实名cstmNo：{}", custNum);
        List<String> custNumList=new ArrayList<>();
        custNumList.add(custNum);
        try {
            JSONObject jsonObject = this.quarterAssetConsumption(custNumList, ChangchunKit.QUARTER_USER_ASSET_SITUATION_URL,year,quarter);
            log.debug("用户季度资产等级：{}", jsonObject);
            if(jsonObject!=null&& !StringUtils.isNullOrEmpty(jsonObject.getString("jdzzcFd"))){
                return jsonObject.getInteger("jdzzcFd");
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("用户季度资产等级数据查询失败：{}", e);
        }
        return null;
    }

    /**季度用户资产情况**/
    private JSONObject quarterAssetConsumption(List custNumlist, String url, int year, int quarter) throws Exception {

        String dateStr =  String.format("%d-%d", year, quarter);
        log.debug("需要查询的时间：dateStr ：{}", dateStr);
        HttpResponse response = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            List list = new ArrayList();
            Map params = new HashMap();
            for (int i = 0; i < custNumlist.size(); i++) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("custNum", String.valueOf(custNumlist.get(i)));
                jsonObject.put("quar", dateStr);
                String encryption = AesUtil.encrypt(String.valueOf(jsonObject));
                list.add(encryption);
                params.put("param" + (i + 1), encryption);
            }
            String json = objectMapper.writeValueAsString(list);
            log.debug("JSON RequestBody: {}", json);

            String sign = SignatureUtil.generateSignature(params, SignVerifyFilter.SECRET_KEY);
            Boolean a = SignatureUtil.verifySignature(params, SignVerifyFilter.SECRET_KEY, sign);
            log.debug("验签结果：{}",a);
            log.debug("接口地址：{}", url);
            HttpRequest body = HttpRequest.post(url)
                    .header("Content-Type", "application/json;charset=utf-8")
                    .header(SignVerifyFilter.SIGNATURE_HEADER, sign)
                    .timeout(10000)
                    .body(json);
            response = body.execute();
        }catch (Exception e){
            e.printStackTrace();
            throw new BizException("网络连接异常,请稍后重试");
        }
        if(response==null){
            throw new BizException("网络连接异常,请稍后重试");
        }
        RsaFgmUtils rsaFgmUtils = new RsaFgmUtils();
        JSONObject respData = JSONObject.parseObject(response.body());
        log.debug("响应结果：{}", response);
        String code = respData.getString("code");
        if ("200".equals(code)){
            String decrypt = null;
            try {
                decrypt = rsaFgmUtils.decryptByPublicKey(RsaFgmUtils.publicKey, respData.getString("data"));
            } catch (Exception e) {
                e.printStackTrace();
                throw new BizException("数据解密失败");
            }
            if(StringUtils.isNullOrEmpty(decrypt)){
                throw new BizException("数据解密失败");
            }
            JSONArray decryptlist = objectMapper.readValue(decrypt, JSONArray.class);
            log.debug("解密后,用户情况：decryptlist：{}", decryptlist);
            return decryptlist.getObject(0, JSONObject.class);
        }else {
            throw new BizException(String.valueOf(response));
        }

    }

}
